package com.hzp.micromall.auth.service.impl;

import com.hzp.micromall.auth.entity.SecurityUser;
import com.hzp.micromall.auth.service.UmsAdminDetailService;
import com.hzp.micromall.auth.service.UmsMemberDetailService;
import com.hzp.micromall.common.core.constant.AuthConstant;
import com.hzp.micromall.common.core.api.ResultCode;
import com.hzp.micromall.common.core.entity.UserDto;
import com.hzp.micromall.common.core.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author houzipeng
 * @Date 2022/2/10 20:40
 * @Version 1.0
 * 用户管理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UmsAdminDetailService adminService;
    @Autowired
    private UmsMemberDetailService memberService;
    @Autowired
    private HttpServletRequest request;

    // TODO: 2022/2/10 是否可以将用户管理改成工场模式

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        UserDto userDto;
        if (AuthConstant.ADMIN_CLIENT_ID.equals(clientId)) {
            userDto = adminService.loadUserByUsername(username);
        } else {
            userDto = memberService.loadUserByUsername(username);
        }
        if (userDto == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        userDto.setClientId(clientId);
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(ResultCode.USER_ACCOUNT_DISABLED.getMessage());
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(ResultCode.USER_ACCOUNT_LOCKED.getMessage());
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(ResultCode.USER_ACCOUNT_EXPIRED.getMessage());
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(ResultCode.TOKEN_INVALID_OR_EXPIRED.getMessage());
        }
        return securityUser;
    }
}
